import React, { useEffect, useRef, useState } from "react";

interface Props {
  value?: Date;
  defaultValue?: Date;
  onChange?: (value: Date) => void;
}

const Calendar = (props: Props) => {
  console.log("render...")
  const { value: propsValue, defaultValue, onChange } = props;
 
  const [value, setValue] = useState(() => {
    // value不存在-非受控
    if (propsValue === undefined) {
      return defaultValue;
    } else {
      return propsValue;
    }
  });
  console.log("value", value)
  const isFirstRender = useRef(true);

  useEffect(() => {
    console.log(propsValue, "propsValue")
    // value不存在且不是第一次渲染
    if(propsValue === undefined && !isFirstRender.current) {
      console.log("useEffect")
      setValue(propsValue);
    }
    isFirstRender.current = false;
  }, [propsValue]);

  const mergedValue = propsValue === undefined ? value : propsValue;
  console.log("mergedValue=propsValue", mergedValue)
  function changeValue(date: Date) {
  // value不存在-非受控
    if (propsValue === undefined) {
      setValue(date);
    }
    onChange?.(date);
  }
  return (
    <div className="mt-4">
      {mergedValue?.toLocaleDateString()}
      <div
        onClick={() => {
          changeValue(new Date("2024-08-15"));
        }}
      >
        2024-08-15
      </div>
      <div
        onClick={() => {
          changeValue(new Date("2024-08-16"));
        }}
      >
        2024-08-16
      </div>
      <div
        onClick={() => {
          changeValue(new Date("2024-08-17"));
        }}
      >
        2024-08-17
      </div>
    </div>
  );
};
export default Calendar;
